package com.herionthenet;

import java.nio.ByteBuffer;

public class SimpleFrameEncoder extends FrameEncoder {

	public static final byte[] TAIL = new byte[]{0x0D, 0x0A};
	public SimpleFrameEncoder() {
		super(TAIL);
	}
	
	@Override
	public ByteBuffer encode(Object message) {
		if(message instanceof String){			
			return doEncode((String)message);
		}
		
		return null;
	}
	
	private ByteBuffer doEncode(String message){
		if(message == null || message.isEmpty())
			new IllegalArgumentException("Invalid message to encode");
		
		int bufferSize = message.length();
		if(header != null)
			bufferSize = bufferSize + header.length;
		
		if(tail != null)
			bufferSize = bufferSize + tail.length;
		
		ByteBuffer buffer = ByteBuffer.allocate(bufferSize);		
		setHeader(buffer);
		buffer.put(message.getBytes());
		setTail(buffer);
		
		return buffer;
	}

}
